﻿using Architecture.Api.Application.Command.UserCommand;
using Architecture.Api.Dtos;
using Architecture.Api.Extensions;
using Architecture.Domain;
using Architecture.Domain.Dto;
using Architecture.Domain.RBAC;
using Architecture.Repository.Impl;
using Architecture.Repository.Migrations;
using Architecture.Service;
using Architecture.Service.Impl;
using Architecture.Service.Interface;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Architecture.Api.Controllers
{
    /// <summary>
    /// 用户API控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {
        readonly IUserService service;

        protected readonly IMediator _mediator;
        protected readonly IConfiguration configuration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service"></param>
        public UserController(IUserService service, IMediator mediator, IConfiguration configuration)
        {
            this.service = service;
            _mediator = mediator;
            this.configuration = configuration;
        }

        #region  省/市/县
        /// <summary>
        /// 截取身份证
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<string> GetBirthDay()
        {
            string idCard = "412723200302062512";

            string num1=idCard.GetBirthDay();

            return num1;
        }
        /// <summary>
        /// 省份表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<Province>>> GetAllProvince()
        {
            ApiResult<List<Province>> result = new ApiResult<List<Province>>();
            try
            {
                result.Data = await service.GetAllProvince();
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 市区表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<Urban>>> GetAllUrban(int? id)
        {
            ApiResult<List<Urban>> result = new ApiResult<List<Urban>>();
            try
            {
                result.Data = await service.GetAllUrban(id);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 县城表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<County>> GetAlCounty(int? id)
        {
            var list = await service.GetAlCounty(id);
            return list;
        }
        #endregion
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userpwd"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult<Information>> Login(string username, string userpwd)
        {
            ApiResult<Information> result = new ApiResult<Information>();
            try
            {
                result.Data = await service.Login(username, userpwd);
                if (result.Data.Gode != 0)
                {
                    string strToken = this.JWTNewString(result.Data.Gode.ToString());
                    result.Data.Token = strToken;
                }
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        //JWT生成Token
        private string JWTNewString(string uid)
        {
            //生成JWT
            //Header，现在签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            //Payload，存放用户信息，下面我们放一个用户id
            var claims =new[] { 
               new Claim(JwtRegisteredClaimNames.Sub,uid),
               new Claim(ClaimTypes.Role,"admin"),
               //new Claim(ClaimTypes.UserData,"测试")
            };
            //Signature
            //取出私有密钥以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"],    //发布者
                audience: configuration["Authentication:Audience"], //接收者
                claims:claims,                                     //存放用户信息
                notBefore:DateTime.UtcNow,                         //发布时间
                expires:DateTime.Now.AddDays(1),              //有效期设置1天
                signingCredentials                      //数字签名
                );
            var TokenStr= new JwtSecurityTokenHandler().WriteToken(Token);

            return TokenStr;
        }

        /// <summary>
        /// 用户信息添加
        /// </summary>
        /// <param name="model">添加实体</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> Create(UserCreateCommand model)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await _mediator.Send(model);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户信息列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<object>> Show([FromQuery]UserShowCommand user)
        {
            ApiResult<object> result = new ApiResult<object>();
            try
            {
                result.Data = await _mediator.Send(user);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult<int>> Delete([FromQuery]UserDeleteCommand id)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await _mediator.Send(id);
            }
            catch (Exception ex)
            {
                result.Code= -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 查询数据详情
        /// </summary>
        /// <param name="id">数据id</param>
        /// <returns>返回数据对象</returns>
        [HttpGet]
        public async Task<ApiResult<UserInfo>> Backfill([FromQuery]UserBackfillCommand id)
        {
            ApiResult<UserInfo> result = new ApiResult<UserInfo>();
            try
            {
                result.Data =await _mediator.Send(id);
            }
            catch (Exception ex)
            {
                result.Code= -1;
                result.Message = ex.Message;
                throw;
            }
            return result;

        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> UpdateAsync(UserUpdateCommand model)
        {
            ApiResult<int> result= new ApiResult<int>();
            try
            {
                result.Data=await _mediator.Send(model);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 员工树形绑定
        /// </summary>
        /// <param name="ids">实体</param>
        /// <returns>返回受影响的数据</returns>
        [HttpPost]
        public async Task<ApiResult<object>> GetInquire(EmployeeCommand ids)
        {
            ApiResult<object> result = new ApiResult<object>();
            try
            {
                result.Data= await _mediator.Send(ids);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        
    }
}
